import {reqCartList, reqDeleteCartById, reqCheckCartById} from '@/api'

const state = {
    cartList: []
}
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList
    }
}
const actions = {
    //获取购物车数据
    async getCartList({commit}) {
        let result = await reqCartList()
        if (result.code === 200) {
            commit('GETCARTLIST', result.data)
        }
    },
    //删除购物车商品
    async deleteCartById({commit}, skuId) {
        let result = await reqDeleteCartById(skuId)
        if (result.code === 200) {
            return 'OK'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //删除全部已选中的商品
    deleteAllChecked({getters, dispatch}) {
        let PromiseAll = []
        //获取购物车中全部产品
        getters.cartList.cartInfoList.forEach((item) => {
            let promise = item.isChecked === 1 ? dispatch('deleteCartById', item.skuId) : ''
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    },
    //更改商品选中属性
    async checkCartById({commit}, {skuId, isChecked}) {
        let result = await reqCheckCartById(skuId, isChecked)
        if (result.code === 200) {
            return 'OK'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //修改全选状态
    updateAllChecked({dispatch, state}, isChecked) {
        let promiseAll = []
        state.cartList[0].cartInfoList.forEach((item) => {
            let promise = dispatch('checkCartById', {skuId: item.skuId, isChecked})
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }
}
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    }
}

export default {
    state,
    mutations,
    actions,
    getters
}
